package com.ruoyi.project.sdi.input.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Lists;
import com.ruoyi.common.constant.PaeaConstants;
import com.ruoyi.common.enums.ImageType;
import com.ruoyi.common.enums.WorkloadType;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.CommonParaTool;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.TaskQueue;
import com.ruoyi.common.utils.security.ShiroUtils;
import com.ruoyi.project.er.domain.PaeaErError;
import com.ruoyi.project.er.enums.PaeaErrorSource;
import com.ruoyi.project.er.service.IPaeaErErrorRegisterService;
import com.ruoyi.project.oms.paeaAuBatch.domain.PaeaAuBatch;
import com.ruoyi.project.oms.paeaAuBatch.enums.AuBatchStatus;
import com.ruoyi.project.oms.paeaAuBatch.service.IPaeaAuBatchService;
import com.ruoyi.project.paea.paeaDsTrade.domain.PaeaDsTrade;
import com.ruoyi.project.paea.paeaDsTrade.service.IPaeaDsTradeService;
import com.ruoyi.project.sdi.input.model.ForceInputBatchInfoVo;
import com.ruoyi.project.sdi.input.model.ManualInputBatchInfoVo;
import com.ruoyi.project.sdi.input.service.IInputService;
import com.ruoyi.project.sdi.scan.enums.AutoErrorDefine;
import com.ruoyi.project.sdi.sdiImage.domain.SdiImage;
import com.ruoyi.project.sdi.sdiImage.service.ISdiImageService;
import com.ruoyi.project.sdi.sdiPaeaArc.domain.SdiPaeaArc;
import com.ruoyi.project.sdi.sdiPaeaArc.enums.ArchivePaeaStatus;
import com.ruoyi.project.sdi.sdiPaeaArc.service.ISdiPaeaArcService;
import com.ruoyi.project.stat.paeaReportWorkload.service.IStatisticsWorkloadService;
import com.ruoyi.project.system.user.domain.User;
import com.ruoyi.project.tool.DateTimeUtil;
import lombok.extern.slf4j.Slf4j;
import net.northking.workitempool.cluster.client.ResultWrapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 功能描述：
 *
 * @author 关晓强
 * @version 1.0
 * @date 2020/3/24 18:28
 */
@Service
@Slf4j
public class InputServiceImpl implements IInputService {

    @Autowired
    private ISdiPaeaArcService sdiPaeaArcService;

    @Autowired
    private ISdiImageService sdiImageService;

    @Autowired
    private IPaeaDsTradeService paeaDsTradeService;

    @Autowired
    private IStatisticsWorkloadService statisticsWorkloadService;

    @Autowired
    private IPaeaErErrorRegisterService paeaErErrorRegisterService;

    @Autowired
    private IPaeaAuBatchService paeaAuBatchService;
    /**
     * 获取指定的补录任务
     * @param arcId
     * @param user
     * @return
     */
    @Override
    @Transactional
    public ManualInputBatchInfoVo obtainManualInputTask(String arcId, User user) {
        SdiPaeaArc sdiPaeaArc = null;
        if ("random".equals(arcId)) {
            //arcId为空时，调用队列获取
            sdiPaeaArc=this.rmiFetchTask(ArchivePaeaStatus.WaitDataInput.getValue(), user);
        } else {
            //arcId不为空时，获取指定Id的批次信息
            sdiPaeaArc = sdiPaeaArcService.getById(arcId);
            if (sdiPaeaArc == null) {
                throw new BusinessException("该记录可能被删除");
            }
            //更新状态
            if ((ArchivePaeaStatus.toArcBatchStatus(sdiPaeaArc.getStatus()) == ArchivePaeaStatus.待重新补录790)
                    || (ArchivePaeaStatus.toArcBatchStatus(sdiPaeaArc
                    .getStatus()) == ArchivePaeaStatus.正在重新补录795)) {
                sdiPaeaArc.setStatus(ArchivePaeaStatus.正在重新补录795.getValue());
            } else {
                sdiPaeaArc.setStatus(ArchivePaeaStatus.DataInputing.getValue());
            }
            sdiPaeaArc.setLocker(user.getUserId());
            sdiPaeaArc.setInputer(user.getUserId());
            sdiPaeaArcService.updateById(sdiPaeaArc);
        }
        //0.数据库查询
        List<SdiImage> sdiImageList = sdiImageService.getSdiImagesBySdiPaeaArc(sdiPaeaArc);
        List<PaeaDsTrade> paeaDsTradeList = paeaDsTradeService.getPaeaDsTradesBySdiPaeaArc(sdiPaeaArc);
        String imageUrlPrefix = CommonParaTool.getImgPathPrefix(sdiPaeaArc.getAuditOrgCode());

        //补录任务信息
        ManualInputBatchInfoVo manualInputBatchInfoVo = new ManualInputBatchInfoVo();

        //1.批次信息
        ManualInputBatchInfoVo.SdiPaeaArcInput sdiPaeaArcInput = new ManualInputBatchInfoVo.SdiPaeaArcInput();
        BeanUtils.copyProperties(sdiPaeaArc, sdiPaeaArcInput);
        sdiPaeaArcInput.setImageUrlPrefix(imageUrlPrefix);
        manualInputBatchInfoVo.setSdiPaeaArcInput(sdiPaeaArcInput);

        //2.影像信息
        sdiImageList.stream().forEach(sdiImage -> {
            ManualInputBatchInfoVo.SdiImageInput sdiImageInput = new ManualInputBatchInfoVo.SdiImageInput();
            BeanUtils.copyProperties(sdiImage, sdiImageInput);
            List<String> compVchNos = Lists.newArrayList();
            paeaDsTradeList.stream().forEach(paeaDsTrade -> {
                if (sdiImage.getId().equals(paeaDsTrade.getImageId())) {
                    ManualInputBatchInfoVo.SdiImageRelTrade sdiImageRelTrade = new ManualInputBatchInfoVo.SdiImageRelTrade();
                    sdiImageRelTrade.setId(paeaDsTrade.getId());
                    sdiImageRelTrade.setTxnAmt(paeaDsTrade.getTxnAmt());
                    sdiImageRelTrade.setVchNo(paeaDsTrade.getVchNo());
                    sdiImageRelTrade.setStatus(paeaDsTrade.getStatus());
                    sdiImageInput.getSdiImageRelTradeList().add(sdiImageRelTrade);
                    compVchNos.add(paeaDsTrade.getVchNo());
                }
            });
            sdiImageInput.setVchNos(StringUtils.join(compVchNos, ","));
            manualInputBatchInfoVo.getSdiImageInputList().add(sdiImageInput);
        });

        //3.流水信息
        paeaDsTradeList.stream().forEach(paeaDsTrade -> {
            ManualInputBatchInfoVo.PaeaDsTradeInput paeaDsTradeInput = new ManualInputBatchInfoVo.PaeaDsTradeInput();
            BeanUtils.copyProperties(paeaDsTrade, paeaDsTradeInput);
            manualInputBatchInfoVo.getPaeaDsTradeInputList().add(paeaDsTradeInput);
        });

        return manualInputBatchInfoVo;
    }

    /**
     * 获取二次补录批次信息
     * @param arcId
     * @param user
     * @return
     */
    @Override
    public ForceInputBatchInfoVo obtainForceInputTask(String arcId, User user) {
        int times = 0;
        while (true) {
            SdiPaeaArc sdiPaeaArc = null;
            if ("random".equals(arcId)) {
                sdiPaeaArc=this.rmiFetchTask(ArchivePaeaStatus.WaitForceInput.getValue(),user);
            } else {
                //arcId不为空时，获取指定Id的批次信息
                sdiPaeaArc = sdiPaeaArcService.getById(arcId);
                if (sdiPaeaArc == null) {
                    throw new BusinessException("该记录可能被删除");
                }
                //更新状态
                sdiPaeaArc.setStatus(ArchivePaeaStatus.ForceInputing.getValue());
                sdiPaeaArc.setLocker(user.getUserId());
                sdiPaeaArc.setForceInputer(user.getUserId());
                sdiPaeaArcService.updateById(sdiPaeaArc);
            }
            if(sdiPaeaArc==null){
                times++;
                continue;
            }
            ForceInputBatchInfoVo forceInputBatchInfoVo = toForceData(user, sdiPaeaArc);
            if (forceInputBatchInfoVo == null) {
                //archive.setName("");
                sdiPaeaArc.setStatus(ArchivePaeaStatus.Complete.getValue());
                sdiPaeaArc.setLocker("-1");
                sdiPaeaArcService.updateById(sdiPaeaArc);
                if (arcId != null) {
                    throw new BusinessException("该任务没有待二次补录的流水，不用二次补录，请重新选择");
                } else {
                    times++;
                    if (times > 3){
                        return null;
                    }
                    arcId = null;
                    continue;
                }
            } else {
                return forceInputBatchInfoVo;
            }
        }
    }


    private ForceInputBatchInfoVo toForceData(User user,SdiPaeaArc sdiPaeaArc) {
        //0.数据库查询
        List<SdiImage> sdiImageList = sdiImageService.getSdiImagesBySdiPaeaArc(sdiPaeaArc);
        List<PaeaDsTrade> paeaDsTradeList = paeaDsTradeService.getPaeaDsTradesBySdiPaeaArc(sdiPaeaArc);
        String imageUrlPrefix = CommonParaTool.getImgPathPrefix(sdiPaeaArc.getAuditOrgCode());
        ForceInputBatchInfoVo forceInputBatchInfoVo = new ForceInputBatchInfoVo();
        //1.批次信息
        ForceInputBatchInfoVo.SdiPaeaArcInput sdiPaeaArcInput = new ForceInputBatchInfoVo.SdiPaeaArcInput();
        BeanUtils.copyProperties(sdiPaeaArc, sdiPaeaArcInput);
        sdiPaeaArcInput.setImageUrlPrefix(imageUrlPrefix);
        forceInputBatchInfoVo.setSdiPaeaArcInput(sdiPaeaArcInput);

        //2.流水信息
        String vchNo = "";
        Map<String, List<SdiImage>> map = this.groupImagesByVchNo(sdiImageList);
        for (PaeaDsTrade paeaDsTrade : paeaDsTradeList) {
            if (paeaDsTrade.getVchNo().equals(vchNo)) {
                // 相同的流水号只取金额最大的一笔进行二次补录
                continue;
            } else {
                vchNo = paeaDsTrade.getVchNo();
            }
            List<SdiImage> sdiImages = map.get(vchNo);
            if (this.needForceInput(sdiImages, paeaDsTrade)) {
                ForceInputBatchInfoVo.PaeaDsTradeInput paeaDsTradeInput = new ForceInputBatchInfoVo.PaeaDsTradeInput();
                BeanUtils.copyProperties(paeaDsTrade,paeaDsTradeInput);
                if (sdiImages.size() > 0) {
                    paeaDsTradeInput.setSdiImageInputList(sdiImages);
                }
                forceInputBatchInfoVo.getPaeaDsTradeInputList().add(paeaDsTradeInput);
            }
        }

        if (forceInputBatchInfoVo.getPaeaDsTradeInputList().size() == 0) {
            log.debug("没有二次补录任务流水！" + sdiPaeaArc.getCode());
            return null;
        }
        return forceInputBatchInfoVo;
    }

    /**
     * 按照流水号分组影像
     * @param sdiImages
     * @return
     */
    public Map<String, List<SdiImage>> groupImagesByVchNo(
            List<SdiImage> sdiImages) {
        Map<String, List<SdiImage>> map = new HashMap<String, List<SdiImage>>();
        Map<String, String> imageIdVchNoMap = new HashMap<String, String>();
        for (SdiImage image : sdiImages) {
            String vchNo = image.getCompTxnSeq();
            if (image.getIsFrontPage() && vchNo != null
                    && vchNo.trim().length() > 0
                    && image.getId().equals(image.getParentId())) {
                imageIdVchNoMap.put(image.getId(), vchNo.trim());
                List<SdiImage> imageList = map.get(vchNo.trim());
                if (imageList == null) {
                    imageList = new ArrayList<SdiImage>();
                    map.put(vchNo, imageList);
                }
                imageList.add(image);
            } else if (image.getParentId() != null) {
                vchNo = imageIdVchNoMap.get(image.getParentId());
                if (vchNo != null) {
                    List<SdiImage> imageList = map.get(vchNo);
                    if (imageList != null)
                        imageList.add(image);
                }

            }
        }
        return map;
    }



    /**
     * 登记缺票
     * @param ids
     */
    @Override
    @Transactional
    public void lostVoucherRegister(String ids) {
        User user = ShiroUtils.getSysUser();
        //更新流水状态为缺票
        List<PaeaDsTrade> paeaDsTrades = this.paeaDsTradeService.list(new QueryWrapper<PaeaDsTrade>()
                    .in("id",Arrays.asList(ids.split(","))));
        paeaDsTrades.stream().forEach(paeaDsTrade -> paeaDsTrade.setStatus(3));
        if(paeaDsTrades!=null && paeaDsTrades.size()>0){
            this.paeaDsTradeService.batchUpdatePaeaDsTrades(paeaDsTrades);
        }
        //记录缺票信息到登记缺票表，调用方法

        //创建缺票差错,报错
        this.createLostVoucherError(paeaDsTrades,user);
    }

    /**
     * 需要强补的判断
     * @param images
     * @param trade
     * @return
     */
    private boolean needForceInput(List<SdiImage> images, PaeaDsTrade trade) {
        if (images == null)
            return false;
        if (images.size() < 1)
            return false;
        SdiImage mainPage = images.get(0);
        String needInputType = PaeaConstants.SYS_CONFIG_MAP.get(PaeaConstants.FORCEINPUT_VOUCHER_TYPE).getConfigValue();
        if(mainPage.getType().matches(needInputType)){
            return true;
        }else{
            return false;
        }
    }

    /**
     * 提交批次
     * @param manualInputBatchInfoVo
     * @return
     */
    @Override
    @Transactional
    public boolean submitManualInputBatch(ManualInputBatchInfoVo manualInputBatchInfoVo) {
        User user = ShiroUtils.getSysUser();
        boolean isCommit = manualInputBatchInfoVo.isCommit;
        //更新影像
        List<ManualInputBatchInfoVo.SdiImageInput> sdiImageInputList = manualInputBatchInfoVo.sdiImageInputList;
        List<SdiImage> sdiImageList = Lists.newArrayList();
        if(StringUtils.isNotEmpty(sdiImageInputList)){
            sdiImageInputList.stream().forEach(sdiImageInput -> {
                SdiImage sdiImage = new SdiImage();
                sdiImage.setId(sdiImageInput.getId());
                sdiImage.setType(sdiImageInput.getType());
                sdiImage.setStatus(sdiImageInput.getStatus());
                sdiImage.setDescription(StringUtils.isNotEmpty(sdiImageInput.getType())?sdiImageInput.getType().substring(0,1):"");
                sdiImage.setIndexNo(sdiImageInput.getIndexNo());
                if(StringUtils.isNotEmpty(sdiImageInput.getSdiImageRelTradeList())){
                    sdiImage.setCompTradeId(sdiImageInput.getSdiImageRelTradeList().get(0).getId());
                }
                sdiImageList.add(sdiImage);
            });
            this.sdiImageService.batchUpdateSdiImages(sdiImageList);
        }
        //更新流水
        List<ManualInputBatchInfoVo.PaeaDsTradeInput> paeaDsTradeInputList = manualInputBatchInfoVo.paeaDsTradeInputList;
        List<PaeaDsTrade> paeaDsTradeList = Lists.newArrayList();
        if(StringUtils.isNotEmpty(paeaDsTradeInputList)) {
            paeaDsTradeInputList.stream().forEach(paeaDsTradeInput -> {
                PaeaDsTrade paeaDsTrade = new PaeaDsTrade();
                paeaDsTrade.setId(paeaDsTradeInput.getId());
                paeaDsTrade.setImageId(paeaDsTradeInput.getImageId());
                paeaDsTrade.setStatus(paeaDsTradeInput.getStatus());
                paeaDsTradeList.add(paeaDsTrade);
            });
            this.paeaDsTradeService.batchUpdatePaeaDsTrades(paeaDsTradeList);
        }
        //更新批次
        ManualInputBatchInfoVo.SdiPaeaArcInput sdiPaeaArcInput =  manualInputBatchInfoVo.sdiPaeaArcInput;
        if(isCommit){
            SdiPaeaArc sdiPaeaArc = this.sdiPaeaArcService.getById(sdiPaeaArcInput.getId());
            sdiPaeaArc.setInputer(user.getUserId());
            sdiPaeaArc.setInputTime(new Date());
            sdiPaeaArc.setLocker("-1");
            sdiPaeaArc.setStatus(ArchivePaeaStatus
                    .toArcBatchStatus(
                            sdiPaeaArcInput.getStatus())
                    .nextStatus().getValue());
            this.sdiPaeaArcService.updateById(sdiPaeaArc);

            //处理主副票父子关系
            this.matchParentIdRel(sdiPaeaArc);
            //通过补录结果与识别结果的对比，得出有效补录工作量
            int changedWorkload = this.countAndUpdateCurrentBatchWorkLoad(sdiPaeaArcInput.getId(),true);
            Date inputDate = new Date(System.currentTimeMillis());
            this.statisticsWorkloadService.writePaeaReportWorkload(user,inputDate, WorkloadType.人工补录,changedWorkload,user.getDeptId());
            //处理批次提交后续工作
            updateAuBatchToInitial(sdiPaeaArc);

        }
        return true;
    }


    //批次提交时更新该批次对应的监督批次状态为待获取
    private void updateAuBatchToInitial(SdiPaeaArc sdiPaeaArc) {
        PaeaAuBatch paeaAuBatch = this.paeaAuBatchService.getOne(new QueryWrapper<PaeaAuBatch>()
                .eq("tr_date", DateTimeUtil.getDateFormat(sdiPaeaArc.getTrDate()))
                .eq("teller_id",sdiPaeaArc.getTellerCode())
                .le("status",AuBatchStatus.Initial.getValue()));
        if(paeaAuBatch!=null){
            paeaAuBatch.setStatus(AuBatchStatus.Initial.getValue()+"");
            this.paeaAuBatchService.updateById(paeaAuBatch);
        }
    }

    /**
     * 二次补录单笔提交
     * @param forceInputBatchInfoVo
     * @return
     */
    @Override
    @Transactional
    public boolean submitForceInputBatch(ForceInputBatchInfoVo forceInputBatchInfoVo) {
        User user = ShiroUtils.getSysUser();

        String tradeId = forceInputBatchInfoVo.getPaeaDsTradeInput().getId();
        PaeaDsTrade paeaDsTrade = paeaDsTradeService.getById(tradeId);
        paeaDsTrade.setWdcmod("1");// 强制补录
        this.paeaDsTradeService.updatePaeaDsTrade(paeaDsTrade);
        if(StringUtils.isNotEmpty(forceInputBatchInfoVo.getErrorMessage())){
                this.createForceInputError(forceInputBatchInfoVo, paeaDsTrade,user);
        }
        Boolean isCommit = forceInputBatchInfoVo.getIsCommit();
        Date scanDate = new Date(System.currentTimeMillis());
        if(isCommit){
            String arcId = forceInputBatchInfoVo.sdiPaeaArcInput.getId();
            SdiPaeaArc sdiPaeaArc = this.sdiPaeaArcService.getById(arcId);
                //强补完成提交时查看批次是否需要待重新补录，如果需要则修改成正在重新补录
                if("needReInput".equals(sdiPaeaArc.getName())){
                    sdiPaeaArc.setStatus(ArchivePaeaStatus.正在重新补录795.getValue());
                    sdiPaeaArc.setLocker(sdiPaeaArc.getInputer());
                }else{
                    sdiPaeaArc.setStatus(ArchivePaeaStatus.toArcBatchStatus(
                            sdiPaeaArc.getStatus()).nextStatus().getValue());
                    sdiPaeaArc.setLocker("-1"); // 解锁
                }

                sdiPaeaArc.setForceInputer(user.getUserId());
                sdiPaeaArc.setForceInputTime(new Date(new java.util.Date()
                        .getTime()));
                sdiPaeaArc.setForceInputNum(forceInputBatchInfoVo.getPaeaDsTradeInputList().size());
                this.sdiPaeaArcService.updateSdiPaeaArc(sdiPaeaArc);
                //提交批次记录批次+1
                this.statisticsWorkloadService.writePaeaReportWorkload(user,scanDate,WorkloadType.强制补录,0,user.getDeptId());
        }
        // 记录补录流水工作量
        this.statisticsWorkloadService.updatePaeaReportWorkloadAdd(user,scanDate,WorkloadType.强制补录,1);
        return true;
    }

    /**
     * 创建缺票差错
     * @param paeaDsTrades
     * @param user
     */
    private void createLostVoucherError(List<PaeaDsTrade> paeaDsTrades, User user) {
        PaeaDsTrade paeaDsTrade = paeaDsTrades.get(0);
        PaeaErError paeaErError = new PaeaErError();
        paeaErError.setCreateBy(user.getUserId());
        paeaErError.setCreateTime(new Date());
        paeaErError.setErrSource(PaeaErrorSource.S人工补录.getValue());
        paeaErError.setTrDate(new java.sql.Date(paeaDsTrade.getTrDate().getTime()));
        paeaErError.setOrgId(paeaDsTrade.getBrCode());
        paeaErError.setTellerId(paeaDsTrade.getTrTelr());
        List<String> paeaErPoints = Lists.newArrayList(AutoErrorDefine.补录缺票风险点.getPaeaErTypeCode(),AutoErrorDefine.补录缺票风险点.getErrorPoint());
        paeaErError.setPaeaErPointIds(paeaErPoints);
        String errorMessgae = "缺票流水："+paeaDsTrades.stream().map(PaeaDsTrade::getVchNo).collect(Collectors.joining(","));
        paeaErError.setAuditProceeding(errorMessgae);
        Date correctLimitDate = CommonParaTool.getCorrectLimitDate();
        paeaErError.setCorrectLimitDate(new java.sql.Date(correctLimitDate.getTime()));

        paeaErError.setTradeId(paeaDsTrade.getImageId());
        paeaErError.setVchNo(paeaDsTrade.getVchNo());
        this.paeaErErrorRegisterService.registerError(paeaErError);
        log.info("日期：" + paeaDsTrade.getTrDate() + " 机构：" + paeaDsTrade.getBrCode() + " 柜员："
                + paeaDsTrade.getTrTelr() + " 风险信息：" + errorMessgae);
    }


    /**
     * 创建二次补录差错
     * @param forceInputBatchInfoVo
     * @param user
     */
    private void createForceInputError(ForceInputBatchInfoVo forceInputBatchInfoVo, PaeaDsTrade paeaDsTrade, User user) {
        PaeaErError paeaErError = new PaeaErError();
        paeaErError.setCreateBy(user.getUserId());
        paeaErError.setCreateTime(new Date());
        paeaErError.setErrSource(PaeaErrorSource.S强制补录.getValue());
        paeaErError.setTrDate(new java.sql.Date(forceInputBatchInfoVo.getPaeaDsTradeInput().getTrDate().getTime()));
        paeaErError.setOrgId(forceInputBatchInfoVo.getPaeaDsTradeInput().getBrCode());
        paeaErError.setTellerId(forceInputBatchInfoVo.getPaeaDsTradeInput().getTellerCode());
        List<String> paeaErPoints = Lists.newArrayList(AutoErrorDefine.二次补录风险点.getPaeaErTypeCode(),AutoErrorDefine.二次补录风险点.getErrorPoint());
        paeaErError.setPaeaErPointIds(paeaErPoints);
        paeaErError.setAuditProceeding(forceInputBatchInfoVo.getErrorMessage());
        Date correctLimitDate = CommonParaTool.getCorrectLimitDate();
        paeaErError.setCorrectLimitDate(new java.sql.Date(correctLimitDate.getTime()));

        paeaErError.setTradeId(paeaDsTrade.getImageId());
        paeaErError.setVchNo(paeaDsTrade.getVchNo());
        this.paeaErErrorRegisterService.registerError(paeaErError);
        log.info("日期：" + forceInputBatchInfoVo.getPaeaDsTradeInput().getTrDate() + " 机构：" + forceInputBatchInfoVo.getPaeaDsTradeInput().getBrCode() + " 柜员："
                + forceInputBatchInfoVo.getPaeaDsTradeInput().getTellerCode() + " 风险信息：" + forceInputBatchInfoVo.getErrorMessage());
    }

    /**
     * 为提交的批次设定主副票关系
     * @param sdiPaeaArc
     */
    private void matchParentIdRel(SdiPaeaArc sdiPaeaArc) {
        List<SdiImage> sdiImageList = this.sdiImageService.getSdiImagesBySdiPaeaArc(sdiPaeaArc);
        String parentId = "";
        for(SdiImage sdiImage : sdiImageList){
            if(ImageType.MAIN.getValue().equals(sdiImage.getDescription())
                    || ImageType.OTHER.getValue().equals(sdiImage.getDescription())){
                parentId = sdiImage.getId();
            }
            sdiImage.setParentId(parentId);
        }
        this.sdiImageService.saveOrUpdateBatch(sdiImageList);
    }


    //提交批次计算有效工作量
    public Integer countAndUpdateCurrentBatchWorkLoad(String arcId,boolean whetherFinish) {
        SdiPaeaArc sdiPaeaArc = this.sdiPaeaArcService.getById(arcId);
        List<SdiImage> sdiImageList = this.sdiImageService.getSdiImagesBySdiPaeaArc(sdiPaeaArc);
        int changedSize = 0;
        changedSize = calculateChanged(sdiImageList,whetherFinish);
        return changedSize;
    }

    private int calculateChanged(List<SdiImage> sdiImageList,boolean whetherFinish) {
        int changedSize = 0;
        List<SdiImage> changedImageList = new ArrayList<SdiImage>();
        for(SdiImage sdiImage : sdiImageList){
            String originalResult = sdiImage.getRectanglle();
            String compareResult = generateCompareResult(sdiImage);
            if(originalResult==null || !originalResult.equals(compareResult)){
                changedSize++;
                if(whetherFinish){
                    sdiImage.setRectanglle(compareResult);
                    changedImageList.add(sdiImage);
                }
            }
        }
        if(whetherFinish && changedImageList !=null && changedImageList.size()>0){
            this.sdiImageService.saveOrUpdateBatch(changedImageList);
        }
        return changedSize;
    }

    private String generateCompareResult(SdiImage sdiImage) {
        String tempTxnSeq=sdiImage.getCompTxnSeq();
        String compareTxnSeq = "";
        String compareResult = sdiImage.getType();
        String [] txnSeqArray =(tempTxnSeq==null?"".split("@"):tempTxnSeq.split("@"));
        if(txnSeqArray.length>1){
            for(String txnSeq : txnSeqArray){
                if(txnSeq.length() > 1){
                    compareTxnSeq = txnSeq;
                }
            }
            if(!"".equals(compareTxnSeq)){
                compareResult = compareResult+"$"+compareTxnSeq;
            }
        }else if(tempTxnSeq!=null && tempTxnSeq.length()>1){
            compareResult = compareResult+"$"+tempTxnSeq;
        }
        return compareResult;
    }

    /**
     * 用workItemPool获取任务
     * @param status
     * @param user
     * @return
     */
    protected SdiPaeaArc rmiFetchTask(int status, User user) {
        try {
            ResultWrapper resultWrapper = TaskQueue.getInstance().obtainWorkItem(status, user);
            if (resultWrapper != null && resultWrapper.ids != null && resultWrapper.ids.length > 0) {
                String arcId = resultWrapper.ids[0];
                SdiPaeaArc sdiPaeaArc=this.sdiPaeaArcService.getById(arcId);
                return sdiPaeaArc;
            } else {
                return null;
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }
}
